package ConcurrentProgramming;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

// 创建一个每5s写一条日志信息到指定文件中
@SuppressWarnings("all")
public class WriteLoggerThread implements Runnable {
    // 指定写入的文件地址 绝对路径，将日志写到log目录下的log.txt文件中
    private final String filePath = "D:\\programm\\javaee\\leetcode\\src\\ConcurrentProgramming\\log\\log.txt";
    private final FileOutputStream fps = new FileOutputStream(new File(filePath));
    private String logInfo;
    private final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd 'at' HH:mm:ss z");

    public WriteLoggerThread() throws FileNotFoundException {
    }

    @Override
    public void run() {
        try {
            while(true) {
                logInfo += Thread.currentThread().getName();
                logInfo += "---";
                logInfo += format.format(new Date(System.currentTimeMillis()));
                logInfo += "\r\n";  // 换行
                fps.write(logInfo.getBytes()); // 创建写入到文件的流对象
                fps.flush(); // 将缓存中内容刷新到硬盘上
                TimeUnit.MILLISECONDS.sleep(5000);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                fps.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 测试
    public static void main(String[] args) throws FileNotFoundException {
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        executorService.execute(new WriteLoggerThread());
        executorService.shutdown();
    }
}
